<template>
  <div class="teamActivity" v-loading="bannerLoading">
    <!-- banner -->
    <div
      class="act-banner"
      :style="{ background: 'url(' + bannerBackground + ')' }"
    ></div>
    <!-- 上传 -->
    <div class="works-upload">
      <h3>投稿上传</h3>
      <div class="upload-con">
        <el-form ref="fileForm" :rules="formRule" v-bind:model="formList">
          <div class="step-t">第一步：作品说明</div>
          <div class="step-detail">
            <el-form-item label="作品标题：" prop="title">
              <el-input
                placeholder="请输入标题"
                v-model="formList.title"
              ></el-input>
            </el-form-item>
            <el-form-item label="作品简介：" prop="desc">
              <el-input
                type="textarea"
                maxlength="200"
                resize="false"
                v-model="formList.desc"
                placeholder="请输入作品简介，不超过200字"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="作品类型：" prop="type">
              <el-select v-model="formList.type">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  >{{ item.label }}</el-option
                >
              </el-select>
            </el-form-item>
          </div>
          <div class="step-t">第二步：上传作品</div>
          <div class="step-detail">
            <el-form-item label="上传作品：" prop="file">
                <!--  -->
              <el-upload
                class="upload-demo"
                ref="fileUpload"
                :action="fileAction"
                :headers="headerCookie"
                :data="uploadFormData"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-upload="beforeUpload"
                :before-remove="beforeRemove"
                :show-file-list="true"
                :on-change="onChange"
                :on-success="successHandler"
                :on-error="failHandle"
                :limit="1"
                accept=".doc,docx,.pdf,.txt,.bmp,.jpg,.png,.zip"
                :auto-upload="false"
                :on-exceed="handleExceed"
              >
                <el-button class="btn-blue">选择文件</el-button>
                <span slot="tip" class="el-upload__tip"
                  >请上传*.doc，*.docx，*.pdf，*.txt，*.bmp，*.jpg，*.png，*.zip格式的文档，限制大小20M。</span
                >
              </el-upload>
            </el-form-item>
          </div>
          <div class="submit-con">
            <el-button
              :class="['btn-blue btn-submit', submitStatus ? 'disableCss' : '']"
              v-on:click="submitContribution"
              :disabled="submitStatus"
              >{{ submitBtnMsg }}</el-button
            >
          </div>
        </el-form>
      </div>
    </div>
    <div class="act-footer">
      <p>本次活动最终解释权归属《中国学术期刊（光盘版）》电子杂志社有限公司</p>
      <p>© 1998-2021 中国知网（CNKI）</p>
    </div>
  </div>
</template>
<script>
import qs from 'qs'
import config from '../../api/apiConfig'
import { getCookie, histroyCookieDel } from '../../plugin/common'
import { contributionStatus, banner } from '../../api/teamActivity/team'
import { jwtToken } from '@/api/teamActivity/team'
import apiconfig from '@/api/apiConfig'
import { mapGetters } from 'vuex'
import axios from 'axios'
export default {
  name: 'team',
  data() {
    return {
      submitStatus: false,
      bannerBase: 'data:image/png;base64,',
      bannerBackground: '',
      bannerLoading: true,
      timeValid: 1, //活动是否在有效期，1有效，0无效
      typeList: {
        doc: 1,
        docx: 1,
        pdf: 1,
        txt: 1,
        bmp: 0,
        jpg: 0,
        png: 0,
        zip: 1,
      },
      submitBtnMsg: '提交投稿',
      // activityId: '4028b2317e57b9ba017e57bb9d820001', //活动id
      fileList: [],
      formList: {
        title: '',
        desc: '',
        type: 0,
      },
      options: [
        {
          value: 0,
          label: '图片',
        },
        {
          value: 1,
          label: '文本',
        },
      ],
      formRule: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          {
            min: 1,
            max: 100,
            message: `长度在1到 100 个字符`,
            trigger: 'blur',
          },
        ],
        desc: [
          { required: true, trigger: 'blur', message: '请输入简介' },
          { min: 1, max: 200, message: `长度在1到 200个字符`, trigger: 'blur' },
        ],
        type: [{ required: true, trigger: 'blur', message: '请选择类型' }],
        file: [],
      },
      headerCookie:{
        Authorization: "Bearer "+(localStorage.getItem('token')
        ? JSON.parse(localStorage.getItem('token'))['JwtToken']
        : '')
      }
    }
  },
  computed: {
    ...mapGetters(['isClientIp']),
    activityCode: function () {
      return this.$route.params.activityCode
    },
    uploadFormData() {
      return {
        activityId: this.activityCode,
        title: this.formList.title,
        introduction: this.formList.desc,
        type: this.formList.type,
        organId: 'sss',
      }
    },
    // headerCookie: function () {
    //   let vm = this
    //   let jwt = localStorage.getItem('token')
    //     ? JSON.parse(localStorage.getItem('token'))['JwtToken']
    //     : ''
    //     console.log(jwt)
    //   return {
    //     Authorization: `Bearer ${jwt}`,
    //   }
    // },
    fileAction: function () {
      return config.MEMBER_API_HOST + `/activity/teamContribution`
    },
  },
  methods: {
    jwtTokened() {
      let vm = this
      return new Promise(() => {
        if (
          getCookie(apiconfig['enveriment']) ||
          window.location.href.indexOf('localhost') > -1
        ) {
          let obj = {}
          if (window.location.href.indexOf('localhost') > -1) {
            obj = {
              EcpToken: apiconfig['DEV_Token'],
              ClientIp: '124.193.98.144' || vm.isClientIp,
              AppId: apiconfig['appid'],
              // ClientId: Vue.$cookies.get("Ecp_ClientId")
              ClientId: '3220308055500668883',
            }
          } else {
            obj = {
              EcpToken: getCookie(apiconfig['enveriment']),
              ClientIp: vm.isClientIp,
              AppId: apiconfig['appid'],
              ClientId: vm.$cookies.get('Ecp_ClientId'),
            }
          }
          if (getCookie(apiconfig['enveriment'])) {
            jwtToken(obj).then((res) => {
              const now = Date.now()
              const { JwtToken, ExpireIn } = res.Content
              const tokenExpireTime = now + ExpireIn * 1000
              let obj = { JwtToken: JwtToken, ExpireIn: tokenExpireTime }
              window.localStorage.setItem('token', JSON.stringify(obj))
            })
          }
        }
      })
    },
    failHandle() {
      let vm = this
      vm.$refs.fileUpload.clearFiles()
    },
    successHandler(res) {
      let vm = this
      vm.$refs.fileUpload.clearFiles() //清除upload文件
      vm.$refs.fileForm.resetFields() //重置表单
      if (res.success) {
        vm.$message({
          type: 'success',
          message: '上传成功',
        })
        vm.submitStatus = true
        vm.submitBtnMsg = '已投稿'
      } else {
        vm.$message({
          type: 'error',
          message: res.content || res.message,
        })
        if (res.errcode === 401) {
          vm.login()
        }
        if (res.errcode === -1) {
          // vm.jwtTokened().then((res) => {
          //   vm.submitContribution()
          // })
          vm.$message({
            type:'error',
            message:"客户端身份认证超,请重新上传!"
          })
        }
      }
    },
    onChange(file, fileList) {
      let vm = this
      vm.fileList = []
      const typeArr = file.name.split('.')
      const type = typeArr[typeArr.length - 1]
      if (vm.typeList[type] == 0 || vm.typeList[type] == 1) {
        if (vm.typeList[type] == vm.formList.type) {
        } else {
          vm.formList.type = vm.typeList[type]
          //   vm.fileList.push(fileList[fileList.length - 1]);
        }
        vm.fileList.push(fileList[fileList.length - 1])
        //   vm.uploadFormData.file(vm.formList.file[0]);
      } else {
        vm.$message({
          type: 'warning',
          message: '请选择指定类型文件',
        })
        vm.$refs.fileUpload.clearFiles()
        return
      }
    },
    beforeUpload(file) {
      const isLt2M = file && file.size / 1024 / 1024 < 20
      console.log(isLt2M)
      if (!isLt2M && file) {
        this.$message.error('文件大小不能超过 20MB!')
      }
      return isLt2M
    },
    handleRemove(file, fileList) {
      this.fileList = []
    },
    handlePreview(file) {},
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      )
    },
    beforeRemove(file, fileList) {
      if (file) {
        return this.$confirm('此操作将永久删除该文件, 是否继续?')
        // , '提示', {
        //   confirmButtonText: '确定',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // }).then(() => {
        //   this.$message({
        //     type: 'success',
        //     message: '删除成功!'
        //   });
        //     this.fileList=[];
        // }).catch(() => {
        //   this.$message({
        //     type: 'info',
        //     message: '已取消删除'
        //   });
        // });
      }

      //   return this.$confirm(`确定移除 ${ file.name }？`);
    },
    submitContribution() {
      let vm = this;
      // let jwt = localStorage.getItem('token')
      //   ? JSON.parse(localStorage.getItem('token'))['JwtToken']
      //   : ''
      // vm.$refs.fileUpload.headers = `Authorization: Bearer ${jwt}`
      //  console.log(jwt)
      vm.$refs.fileForm.validate((valid) => {
        if (valid) {
          if (vm.fileList.length == 0) {
            vm.$message({
              type: 'error',
              message: '请选择文件!',
            })
            return
          } else {
            vm.$refs.fileUpload.submit()
          }
        }
      })
    },
    getBanner() {
      let vm = this
      banner(vm.activityCode).then((res) => {
        /**
         * enable:1活动有效未过期
         * enable:0活动无效已过期
         */
        vm.timeValid = res.content.enable
        if (vm.timeValid - 0 == 0) {
          vm.submitStatus = true
          vm.submitBtnMsg = '活动已过期'
        }

        let img = res.content.bannerImgId
        if (img) {
          let fileAddress = config['fileHost']
          axios
            .get(fileAddress + '/file/' + img)
            .then((res) => {
              vm.bannerBackground = vm.bannerBase + res.data.content
            })
            .finally(function () {
              vm.bannerLoading = false
            })
        }
      })
    },
    getSubmit() {
      let vm = this
      contributionStatus(vm.activityCode).then((res) => {
        if (res && res.success) {
          vm.submitStatus = false
          vm.submitBtnMsg = '提交投稿'
        } else {
          vm.submitStatus = true
          vm.formList.title = res.content.title
          vm.formList.desc = res.content.introduction
          vm.submitBtnMsg = '已投稿'
        }
      })
    },
    contributionBtn() {
      if (!getCookie(config['enveriment'])) {
        let newHref =
          config['YX_WEB'] +
          '/search/common/login?returnUrl=' +
          config['returnURLTeam'] +
          this.activityCode
        '?appId=' + config['appid']
        window.location.href = newHref
      } else {
        this.active = false
      }
    },
    login() {
      let newHref =
        config['YX_WEB'] +
        '/search/common/login?returnUrl=' +
        config['returnURLTeam'] +
        this.activityCode +
        '?appId=' +
        config['appid']
      window.location.href = newHref
    },
    /**
     *
     */
  },
  mounted() {
    let vm = this
    window.addEventListener('setItemEvent', function (e) {
      if (e.key === 'token') {
        console.log("token"+e.newValue)
        let jwt =JSON.parse(e.newValue)['JwtToken']
        vm.headerCookie={
        Authorization: "Bearer "+jwt
        }
      }
    })
    // vm.jwtTokened();
    if (window.location.href.indexOf(config['enveriment']) > 0) {
      let lid = qs.parse(window.location.href.split('?')[1])
      let calLID =
        lid[config['enveriment']] || lid[config['enveriment'].toLowerCase()]
      if (calLID) {
        // vm.$cookies.set(
        //   config['enveriment'],
        //   decodeURIComponent(calLID),
        //   60 * 60 * 24,
        //   '/',
        //   '192.168.50.179'
        // )
        vm.$cookies.set(
          config['enveriment'],
          decodeURIComponent(calLID),
          60 * 60 * 24,
          '/',
          '.cnki.net'
        )
        histroyCookieDel()
      }
    }
    vm.getBanner()
    // if (getCookie(config['enveriment'])) {
    vm.getSubmit()
    // }
  },
}
</script>
<style scoped>
.act-banner {
  height: 450px;
  background: url(/style/images/src/assets/winterActivity/images/banner.png) top
    center no-repeat;
  background-size: cover !important;
  background-position: top center !important;
}
.submit-con .disableCss,
.submit-con .disableCss:hover {
  background-color: #fff;
  border-color: #ebeef5;
  color: #999;
}
.works-upload {
  width: 1200px;
  margin: 0 auto;
  padding-top: 20px;
}
</style>